//
//  JTableViewBottomView.m
//  IfengNews
//
//  Created by Ryan on 14-1-28.
//
//

#import "JTableBottomView.h"
#import "JTableView.h"
#import "JTableRefrashIndicater.h"
#import "CLGloble.h"

#define JTableBottomMoreView_Height 50.0f


@interface JTableBottomView ()

@property (nonatomic,weak) JTableView *scrollView;
@property (nonatomic,strong) JTableRefrashIndicater *indicater;
@property (nonatomic,strong) UILabel *wordLabel;
@property (nonatomic,strong) UIImageView *separatorLine;

@end

@implementation JTableBottomView


- (id)init{
    self = [super init];
    if(self){
        self.frame=CGRectMake(0, 0, GlobleWidth, JTableBottomMoreView_Height);
        self.isAutoReflash=YES;
        
        
        self.indicater = [JTableRefrashIndicater new];
        self.indicater.frame=
        CGRectMake(105.0f, (JRefrashTableBottomMoreView_Height - 17.0f)/2.0f, 17.0f, 17.0f);
        [self.indicater setLogoState:JTableRefrashIndicaterStateImg];
        self.indicater.autoresizingMask =
        UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleRightMargin;
        //[_indicater stopAnimationOnComplete:nil isSucc:YES animated:YES];
        [self addSubview:self.indicater];
        
        _state = JTableViewLoadMoreStateNormal;
        
        _wordLabel =
        [[UILabel alloc] initWithFrame:CGRectMake(_indicater.right+15, _indicater.top, 110, _indicater.height)];
        _wordLabel.autoresizingMask = _indicater.autoresizingMask;
        _wordLabel.font = [UIFont systemFontOfSize:16];
        _wordLabel.backgroundColor = [UIColor clearColor];
        _wordLabel.textColor = [UIColor colorWithRed:0x6a/255.0f green:0x6a/255.0f blue:0x6a/255.0f alpha:1.0f];
        //wordLabel.bOptimize = YES;
        [self addSubview:_wordLabel];
        
        // 上面的一条分割线
        _separatorLine =[[UIImageView alloc] initWithImage:nil];
        _separatorLine.frame = CGRectMake(INDEX_CELL_LEFT_MARGIN, 0, GlobleWidth-2*INDEX_CELL_LEFT_MARGIN, 0.5);
        [self addSubview:_separatorLine];
        [self updateCSS];

    }
    
    return self;
}

- (void)hiddenSeperatorLine{
    _separatorLine.hidden=YES;
}

- (void)setHidden:(BOOL)hidden{
    
    [super setHidden:hidden];
}

- (BOOL)isLoading{
    return _state==JTableViewLoadMoreStateLoading;
}



- (void)setObserverScrollView:(JTableView *)ascrollView{
    
    
    
    // [self.scrollView removeObserver:self forKeyPath:@"contentOffset" context:nil];
    self.scrollView=ascrollView;
    [self.scrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
   
}

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{
    if (![@"contentOffset" isEqualToString:keyPath]) return;
    if(_state==JTableViewLoadMoreStateLoading || self.hidden==YES) return;
    if(self.scrollView.contentSize.height<self.scrollView.height){
        //当数据过少时底部上拉隐藏 by wfm
        self.indicater.hidden = YES;
        self.wordLabel.hidden = YES;
        return;
    }
    else{
        self.indicater.hidden = NO;
        self.wordLabel.hidden = NO;
    }
    if(_isAutoReflash){
        
       
        
        float originYOfMoreViewShow=
        self.scrollView.contentSize.height-self.scrollView.frame.size.height-self.frame.size.height;
        
        
      
        if(self.scrollView.contentOffset.y>self.scrollView.contentInset.top&&
           originYOfMoreViewShow>60 &&
           (_scrollView.contentOffset.y-originYOfMoreViewShow)>0){
            [self changeState:JTableViewLoadMoreStateLoading];
            if(_scrollView && [_scrollView respondsToSelector:@selector(JRefrashTableBottomMoreViewStartLoading)]){
                [_scrollView performSelector:@selector(JRefrashTableBottomMoreViewStartLoading)];
            }
        }
    }else{
        float offsetY=self.scrollView.contentOffset.y-self.scrollView.contentSize.height+self.scrollView.height;
        if(offsetY<0)return;
        if(self.scrollView.isDragging){
      
            if(_state == JTableViewLoadMoreStatePulling && offsetY<64.0f){
                [self setState:JTableViewLoadMoreStateNormal];
            }else if (_state == JTableViewLoadMoreStateNormal && offsetY >= 64.0f){
                [self changeState:JTableViewLoadMoreStatePulling];
            }
        }else{
            if (_state == JTableViewLoadMoreStatePulling){
                [self changeState:JTableViewLoadMoreStateLoading];
                _isAutoReflash=YES;
                if(_scrollView && [_scrollView respondsToSelector:@selector(JRefrashTableBottomMoreViewStartLoading)]){
                    //[_scrollView performSelector:@selector(JRefrashTableBottomMoreViewStartLoading)];
                    [_scrollView performSelector:@selector(JRefrashTableBottomMoreViewStartLoading)
                                      withObject:nil
                                      afterDelay:0.3];
                }
            }
            

        }
    }
}

- (void)finishWithScuessLoading:(UIScrollView *)scrollView{
    if (self.state != JTableViewLoadMoreStateLoading)
        return;
    
    //[self changeState:JTableViewLoadMoreStateNormal];
    
    [self.indicater setLogoState:JTableRefrashIndicaterStateImg];
    [_indicater stopInfinitAnimation];
    self.wordLabel.text=@"加载成功";
    JTableBottomView __weak *me=self;
    double delayInSeconds = 0.3;
                dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
                dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                    [me changeState:JTableViewLoadMoreStateNormal];
                    if(self.scrollView && [self.scrollView respondsToSelector:@selector(JRefrashTableBottomMoreViewStopLoading)])
                        [self.scrollView performSelector:@selector(JRefrashTableBottomMoreViewStopLoading)];
    });
    

}

- (void)setAuto:(BOOL)isAuto{
    if(isAuto){
        self.wordLabel.text=@"正在载入...";
        self.isAutoReflash=YES;
    }else{
        self.wordLabel.text=@"上拉加载";
        self.isAutoReflash=NO;
    }
}

- (void)finishWithFailLoading:(UIScrollView *)scrollView{
    if (self.state != JTableViewLoadMoreStateLoading)
        return;
    [self.indicater setLogoState:JTableRefrashIndicaterStateImgFail];
    [_indicater stopInfinitAnimation];
    self.wordLabel.text=@"加载完毕";
    self.isAutoReflash=NO;
    JTableBottomView __weak *me=self;
    double delayInSeconds = 0.3;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [me changeState:JTableViewLoadMoreStateNormal];
        if(self.scrollView && [self.scrollView respondsToSelector:@selector(JRefrashTableBottomMoreViewStopLoading)])
            [self.scrollView performSelector:@selector(JRefrashTableBottomMoreViewStopLoading)];
    });


    
}

- (void)finishWithNothingLoading:(UIScrollView *)scrollView{
    if (self.state != JTableViewLoadMoreStateLoading)
        return;
    [self.indicater setLogoState:JTableRefrashIndicaterStateImgFail];
    [_indicater stopInfinitAnimation];
    self.wordLabel.text=@"加载完毕";
    self.isAutoReflash=NO;
    JTableBottomView __weak *me=self;
    double delayInSeconds = 0.3;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [me changeState:JTableViewLoadMoreStateNormal];
        if(self.scrollView && [self.scrollView respondsToSelector:@selector(JRefrashTableBottomMoreViewStopLoading)])
            [self.scrollView performSelector:@selector(JRefrashTableBottomMoreViewStopLoading)];
    });
    
    
    
}


- (void)finishWithSuccessLoadingNoAuto:(UIScrollView *)scrollView{
    if (self.state != JTableViewLoadMoreStateLoading)
        return;
    [self.indicater setLogoState:JTableRefrashIndicaterStateImgFail];
    [_indicater stopInfinitAnimation];
    self.wordLabel.text=@"加载成功";
    self.isAutoReflash=NO;
    JTableBottomView __weak *me=self;
    double delayInSeconds = 0.3;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [me changeState:JTableViewLoadMoreStateNormal];
        if(self.scrollView && [self.scrollView respondsToSelector:@selector(JRefrashTableBottomMoreViewStopLoading)])
            [self.scrollView performSelector:@selector(JRefrashTableBottomMoreViewStopLoading)];
    });
    
    
    
}

- (void)reset:(BOOL)autoload{
    [self changeState:JTableViewLoadMoreStateNormal];
    self.isAutoReflash=autoload;
}

- (void)finishWithNoMoreData:(UIScrollView *)scrollView{
    if (self.state != JTableViewLoadMoreStateLoading)
        return;
    self.isAutoReflash=NO;
    [self changeState:JTableViewLoadMoreStateNoMore];
    
    if(self.scrollView && [self.scrollView respondsToSelector:@selector(JRefrashTableBottomMoreViewStopLoading)])
        [self.scrollView performSelector:@selector(JRefrashTableBottomMoreViewStopLoading)];
    
}



- (void)removeObserverScrollView:(JTableView *)ascrollView{
    
    [ascrollView removeObserver:self forKeyPath:@"contentOffset" context:nil];
    
}

- (void)changeState:(JTableViewLoadMoreState ) aState{
    if(_state == aState) return;
    _state=aState;
    
    switch (_state) {
        case JTableViewLoadMoreStateLoading:
            [self.indicater setLogoState:JTableRefrashIndicaterStateImg];
            [_indicater starInfinitAnimation];
            self.wordLabel.text=@"正在载入...";
            
            break;
            
        case JTableViewLoadMoreStateNormal:
            [self.indicater setLogoState:JTableRefrashIndicaterStateImg];
            [_indicater stopInfinitAnimation];
            self.wordLabel.text=@"上拉加载";
            break;
            
        case JTableViewLoadMoreStateNoMore:
            [self.indicater setLogoState:JTableRefrashIndicaterStateImgFail];
            [_indicater stopInfinitAnimation];
            self.wordLabel.text=@"没有更多内容";
            break;
            
        case JTableViewLoadMoreStatePulling:
            [self.indicater setLogoState:JTableRefrashIndicaterStateImg];
            [_indicater stopInfinitAnimation];
            self.wordLabel.text=@"释放加载";
            
            break;
            
        default:
            break;
    }
    
}

- (void)updateCSS{
    //self.backgroundColor=ICurrentTheme.globleStyle.indexTableColor;
//    [self setNightBlock:^(UIView *me, BOOL isDay) {
//        ((JTableBottomView *)me).backgroundColor=isDay?RGB(0xf7, 0xf7, 0xf7):RGB(36.f, 36.f, 36.f);
//    }];
    [self.indicater updateCSS];
    //_wordLabel.textColor = ICurrentTheme.listStyle.listReflashTextColor;
//    [_wordLabel setNightBlock:^(UIView *me, BOOL isDay) {
//        ((UILabel *)me).textColor=isDay?[UIColor colorWithRed:0x86/255.0f green:0x86/255.0f blue:0x86/255.0f alpha:1.0f]:
//        [UIColor colorWithRed:0x63/255.0f green:0x6e/255.0f blue:0x7c/255.0f alpha:1.0f];
//    }];
   // _separatorLine.image = [UIImage imageNamed:ICurrentTheme.cellStyle.indexCellSeperator];
//    [_separatorLine setNightBlock:^(UIView *me, BOOL isDay) {
//        ((UIImageView *)me).image=isDay?[UIImage imageNamed:@"seperator_line.png"]:
//        [UIImage imageNamed:@"seperator_line_night.png"];
//    }];
}

@end
